<template>
	<view class="work-container no-scroll" :style="{'height':system.windowHeight - system.statusBarHeight - 50 +'px'}">
		<topMenu title="结算单" :show-back="false" :menu="menu" @switchMenu="handleMenuClick"></topMenu>

		<view class="container">
			<u-tabs :list="tabs" current="0" @click="click"></u-tabs>
			<view class="list">
				<view class="thead"  style="background: #fff; border-radius: 12rpx; box-shadow: 0 2rpx 8rpx #eee; padding: 24rpx; display: flex; align-items: center;">
					<view style="flex: 1; text-align: center;">
						<text style="font-weight: bold;">商户名</text>
					</view>
					<view style="flex: 1; text-align: center;">
						<text style="font-weight: bold;">结算时间</text>
					</view>
					<view style="flex: 1; text-align: center;">
						<text style="font-weight: bold;">应收货款</text>
					</view>
					<view style="flex: 1; text-align: center;">
						<text style="font-weight: bold;">状态</text>
					</view>
				</view>
				
				<u-empty mode="data" icon="data" v-show="settList== [] || settList == null">
				</u-empty>
				<view class="data" >
					<u-list @scrolltolower="scrolltolower">
						<u-list-item v-for="item in settList" :key="item.id">
							<view @click="goDetail(item.id)" style="background: #fff; border-radius: 12rpx; box-shadow: 0 2rpx 8rpx rgb(214, 215, 217); padding: 48rpx 24rpx; display: flex; align-items: center;">
								<view style="flex: 1; text-align: center;">
									<text style="font-weight: bold;">{{ item.shopName }}</text>
								</view>
								<view style="flex: 1; text-align: center;">
									<text>{{ item.start+' '+item.end }}</text>
								</view>
								<view style="flex: 1; text-align: center;">
									<text>{{ item.amount || '-' }}</text>
								</view>
								<view style="flex: 1; text-align: center;">
									<text>{{ item.isReceivePayment == 0 ? '收款中':'已收款' }}</text>
								</view>
							</view>
						</u-list-item>
						</u-list>
					<!-- <u-swipe-action> -->
						<view  style="">
							<!-- <u-swipe-action-item :options="[
					      { text: '删除', style: { background: '#dd524d', color: '#fff' } }
					    ]" @click="handleAction($event, item)"> -->
								
							<!-- </u-swipe-action-item> -->
						</view>
					<!-- </u-swipe-action> -->
				</view>
			
			</view>
			
			
		</view>

		<u-popup :closeable="true" :close-on-click-overlay="true" @close="closeAdd" :show="showAdd" :round="10" mode="center" z-index="99" overlayStyle="z-index:90">
			<view class="" style="width: 500rpx;min-height: 100rpx;">
				<view class="title">添加结算单</view>
				<!-- <view class="content"> -->
				<view>
					<u-cell title="商户名" :value="selectedValue.shopName" @tap="showPickers('name')">
						<u-icon slot="right-icon" name="arrow-right" />
					</u-cell>
					<u-cell title="收款类型" :value="selectedValue.type" @tap="showPickers('type')">
						<u-icon slot="right-icon" name="arrow-right" />
					</u-cell>
					<u-cell title="开始日期" :value="selectedValue.start" @tap="showPickers('start')">
					</u-cell>
					<u-cell title="结束日期" :value="selectedValue.end" @tap="showPickers('end')">
					</u-cell>
					<u-cell title="应收款项" :value="selectedValue.amount">
						<u-icon slot="right-icon" name="arrow-right" />
					</u-cell>
				</view>

				<view class="bottom">
					<view class="cancel" @tap.stop="closeAdd">取消</view>
					<view class="success" @tap.stop="handleSuccess">确认</view>
				</view>
				<!-- </view> -->
			</view>
		</u-popup>
		<u-picker :show="showPicker" :showToolbar="true" mode="selector" :columns="[selectList]" keyName="name" @confirm="onPickerConfirm" @cancel="()=> showPicker = false" />
		<u-datetime-picker @confirm="onDateConfirm" @cancel="()=> showDatePicker = false" :show="showDatePicker" v-model="nows" mode="date"></u-datetime-picker>
	</view>
</template>

<script>
	const app = getApp();
	import {
	  getSettlementList,
	  addSettlement,
	  updateSettlement,
		getOrderList
	} from '@/api/mine/settlement';
	import {
	  parseDate
	} from '@/utils/utils';
	import {
	  getCompany
	} from '@/api';
	export default {
	  data() {
	    return {
	      system: app.globalData.system,
	      menu: [{
	        name: '创建结算单',
	        code: 1
	      }],
	      tabs: [{
	          name: 'ALL'
	        },
	        {
	          name: '结算中'
	        },
	        {
	          name: '未结算'
	        },
	      ],
	      typeList: [{
	          label: "货款",
	          name: "货款"
	        },
	        {
	          label: "菜款",
	          name: "菜款"
	        },
	        {
	          label: "其他",
	          name: "其他"
	        }
	      ],
	      flag: 'start',
	      selectedValue: {
	        shopId: null,
	        shopName: null,
					type:null,
	        start: null,
	        end: null,
					amount:null,
					orderIds:null
	      },
				nows:parseDate(new Date()),
	      showPicker: false,
	      showDatePicker: false,
	      showAdd: false,
				selectList:[],
	      companyList: [],
	      settList: [],
	      query: {
	        pageSiz: 15,
	        pageNum : 1,
					isReceivePayment:null
	      }
	    }
	  },
	  created() {
			this.$modal.loading('加载中')
	    this.init()
	  },
	  methods: {
	    handleMenuClick(code) {
	      switch (code) {
	      case 1:
	        this.showAdd = true
	        break;
	      }
	    },
			goDetail(id){
				this.$tab.navigateTo('/pages/work/details/details?id='+id)
			},
	    init() {
	      this.getCompanyList()
				this.getSettList(this.query)
				this.$modal.closeLoading()
	    },
			async getOrder(query){
				const res =await getOrderList(query)
				let amount = 0;
				let orderIds= []
				res.rows.forEach((item,index)=>{
					item.detailList.forEach((it,i)=>{
						amount += parseFloat(it.shopAmount);
					})
					orderIds.push(item.id);
				})
				if(orderIds.length == 0){
					this.$modal.msg('所选时间没有订单')
				}
				console.log("amount==>",amount)
				this.$nextTick(()=>{
					this.$set(this.selectedValue,'orderIds',orderIds.length == 0? null:orderIds)
					this.$set(this.selectedValue,'amount',amount)
				})
				
			},
	    async getSettList() {
	      const res = await getSettlementList(this.query)
				
	      this.settList = res.rows
	    },
	    async getCompanyList() {
	      const res = await getCompany({
	        type: 1
	      })
	      this.companyList = res.rows
	    },
	    click(e) {
				let index = e.index
				if(index == 0){
					this.query.isReceivePayment = null
				}
				if(index == 1){
					this.query.isReceivePayment = '0'
				}
				if(index == 2){
					this.query.isReceivePayment = '1'
				}
				this.getSettList()
	    },
	    closeAdd() {
	      this.showAdd = false
	    },
	    showPickers(flag = "") {
				this.flag = flag
				this.selectList = flag == 'type'? this.typeList : this.companyList
	      if (flag == "name" || flag == "type") {
	        this.showPicker = true
	      } else {
	        this.showDatePicker = true
					if(this.selectedValue.start != null && flag == 'start'){
						this.nows = this.selectedValue.start
					}
					if(this.selectedValue.end != null && flag == 'end'){
						this.nows = this.selectedValue.end
					}
	        console.log(this.selectedValue[flag])
	      }
	    },
	    onPickerConfirm(e) {
	      console.log(e.value[0])
				if(this.flag == 'name'){
					const {
					  id,
					  name
					} = e.value[0]
					this.selectedValue.shopId = id
					this.selectedValue.shopName = name
				}else{
					this.selectedValue.type = e.value[0].name
				}
	      this.showPicker = false
	    },
	    onDateConfirm(e) {
	      let select = parseDate(new Date(e.value))
	      console.log("selectedValue.start===>", this.selectedValue.start)
	      if (this.selectedValue.start != null && this.selectedValue.end != null) {
	        let start = this.flag == 'start' ? e.value : new Date(this.selectedValue.start).getTime()
	        let end = this.flag == 'end' ? e.value : new Date(this.selectedValue.end).getTime()
	        if (start > end) {
	          this.$nextTick(() => {
	            this.$set(this.selectedValue, 'start', parseDate(new Date(end)))
	            this.$set(this.selectedValue, 'end', parseDate(new Date(start)))
							this.getOrder({
								merchantId: this.selectedValue.shopId,
								isSettlement: '0',
								type: 1,
								start: this.selectedValue.start,
								end: this.selectedValue.end,
							})
	          })
	        } else {
	          this.$nextTick(() => {
	            this.$set(this.selectedValue, this.flag, parseDate(new Date(select)))
							this.getOrder({
								merchantId: this.selectedValue.shopId,
								isSettlement: '0',
								type: 1,
								start: this.selectedValue.start,
								end: this.selectedValue.end,
							})
	          })
	        }
					
	      } else {
	        this.$set(this.selectedValue, this.flag, select)
					if(this.selectedValue.start != null && this.selectedValue.end !=null){
						this.getOrder({
							merchantId: this.selectedValue.shopId,
							isSettlement: '0',
							type: 1,
							start: this.selectedValue.start,
							end: this.selectedValue.end,
						})
					}
					
	      }
	      this.showDatePicker = false
				
	    },
	    async handleSuccess() {
				const res = await addSettlement(this.selectedValue)
				this.$modal.msg(res.msg)
				this.showAdd = false
				this.getSettList()
				console.log(res)
	    },
			scrolltolower(){
				if(this.settList.length%this.query.pageSiz == 0){
					this.$nextTick(()=>{
						this.$set(this.query,'pageNumber',this.query.pageNumber++)
						this.getSettList()
					})
				}
				this.getSettList()
			}
	  }
	}
</script>

<style lang="scss" scoped>
	::v-deep .u-tabs__wrapper__nav__item {
	  flex: 1;
	}

	.u-tabs {
	  border-bottom: 1rpx solid $line-color;
	}

	.work-container {
	  background-color: #fff;
	}
</style>